package com.mezz.bones.im.logic.repository.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mezz.bones.framework.core.helper.SnowflakeIdGeneratorHelper;
import com.mezz.bones.im.common.message.body.in.ConversationRecordReq;
import com.mezz.bones.im.common.message.body.in.ConversationRemoveReq;
import com.mezz.bones.im.common.message.body.in.ConversationTopReq;
import com.mezz.bones.im.common.util.MessageUtil;
import com.mezz.bones.im.common.util.SessionIdUtil;
import com.mezz.bones.im.logic.domain.response.ApiMessageUnReadCountResponse;
import com.mezz.bones.im.logic.mapper.IChatConversationMapper;
import com.mezz.bones.im.logic.domain.bo.ChatConversationInitBo;
import com.mezz.bones.im.logic.domain.bo.ChatConversationLatestDataBo;
import com.mezz.bones.im.logic.domain.entity.ChatConversation;
import com.mezz.bones.im.logic.repository.IChatConversationRepository;
import com.mezz.bones.im.logic.repository.IChatUserRepository;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * IM会话列表 服务实现类
 * </p>
 *
 * @author mezz
 * @since 2024-12-20
 */
@Service
public class ChatConversationRepositoryImpl extends ServiceImpl<IChatConversationMapper, ChatConversation> implements IChatConversationRepository {

    @Resource
    private IChatUserRepository chatUserRepository;

    @Resource
    private SnowflakeIdGeneratorHelper snowflakeIdGeneratorHelper;

    @Override
    public ChatConversation getByUserIdAndPeerId(String userId, String peerId) {
        LambdaQueryWrapper<ChatConversation> q = new LambdaQueryWrapper<>();
        q.eq(ChatConversation::getUserId, userId);
        q.eq(ChatConversation::getPeerId, peerId);
        return getOne(q);
    }


    /**
     * 初始化单聊会话
     *
     * @param chatConversationInitBo
     */
    @Override
    public ChatConversation initPrivateConversation(ChatConversationInitBo chatConversationInitBo) {

        Date now = chatConversationInitBo.getNow();

        ChatConversation conversation = new ChatConversation();
        conversation.setChannelType(MessageUtil.channelType(chatConversationInitBo.getUserType(), chatConversationInitBo.getPeerType()));
        conversation.setUserId(chatConversationInitBo.getUserId());
        conversation.setUserType(chatConversationInitBo.getUserType());
        conversation.setPeerId(chatConversationInitBo.getPeerId());
        conversation.setPeerType(chatConversationInitBo.getPeerType());

        conversation.setRelationId(chatConversationInitBo.getRelationId());
        conversation.setRelationType(chatConversationInitBo.getRelationType());

        conversation.setCursorId(snowflakeIdGeneratorHelper.nextId());
        conversation.setSessionId(SessionIdUtil.buildSessionId(chatConversationInitBo.getUserId(), chatConversationInitBo.getPeerId()));
        conversation.setSessionType(chatConversationInitBo.getSessionTypeEnum().getCode());

        conversation.setLastMsgKey("0");
        conversation.setLastMsgSeq("0");
        conversation.setLastPeerReadSeq("0");
        conversation.setLastMsgContent("");
        conversation.setLastMsgTime(new Date());

        conversation.setUnreadCount(0);
        conversation.setTopFlag(0);
        conversation.setCreateTime(now);
        conversation.setUpdateTime(now);
        conversation.setHidden(0);
        this.save(conversation);
        return conversation;
    }

    @Override
    public void updateChatConversation(ChatConversationLatestDataBo bo) {
        //更新会话信息
        ChatConversation update = new ChatConversation();
        update.setId(bo.getId());
        update.setLastMsgKey(bo.getLastMsgKey());
        update.setLastMsgContent(bo.getLastMsgContent());
        update.setLastMsgSeq(bo.getLastMsgSeq());
        update.setLastMsgTime(bo.getLastMsgTime());
        update.setUpdateTime(bo.getLastMsgTime());
        update.setCursorId(bo.getCursorId());

        //会默认展示出来 如果用户之前是删过会话
        update.setHidden(0);
        this.updateById(update);

    }

    @Override
    public void updateConversationUnreadNum(String conversationId, Integer changeNum) {
        this.baseMapper.updateConversationUnreadNum(conversationId, changeNum);
    }

    @Override
    public void clearConversationUnreadNum(String conversationId) {

        ChatConversation update = new ChatConversation();
        update.setId(conversationId);
        update.setUnreadCount(0);
        update.setUpdateTime(new Date());
        this.updateById(update);
    }

    @Override
    public List<ChatConversation> findUserConversationPage(ConversationRecordReq req) {

        if(req.getFetchNum() == null){
            //默认200个会话
            req.setFetchNum(200);
        }

        LambdaQueryWrapper<ChatConversation> q = new LambdaQueryWrapper<>();
        q.eq(ChatConversation::getUserId, req.getUserId());

        if(req.getCustomService() != null ){

            //单聊客服消息
            q.ne(req.getCustomService() == 1, ChatConversation::getRelationType,-1);

            //单聊-普通消息
            q.eq(req.getCustomService() == 0, ChatConversation::getRelationType,-1);
        }

        q.eq(req.getSessionType() != null,ChatConversation::getSessionType,req.getSessionType());
        q.eq(StrUtil.isNotBlank(req.getPeerId()),ChatConversation::getPeerId,req.getPeerId());
        //默认展示用户可见的数据
        q.eq(ChatConversation::getHidden, 0);
        //第二页开始 过滤游标信息

        if(Objects.nonNull(req.getCursorId())){

            //历史数据
            q.lt(req.getFetchMode() == 0, ChatConversation::getCursorId,req.getCursorId());

            //最新数据(可能网络问题 重新拉取数据信息 )
            q.gt(req.getFetchMode()  == 1, ChatConversation::getCursorId,req.getCursorId());

        }

        q.orderByDesc(ChatConversation::getTopFlag);
        q.orderByDesc(ChatConversation::getCursorId);
        q.last(" limit " + req.getFetchNum());
        return this.list( q);
    }

    @Override
    public void removeConversation(ConversationRemoveReq req) {

        ChatConversation update = new ChatConversation();
        update.setId(req.getConversationId());
        //会话删除 未读数也要清零
        update.setUnreadCount(0);
        update.setHidden(1);
        Date now = new Date();
        update.setHiddenTime(now);
        update.setUpdateTime(now);
        this.updateById(update);
    }

    @Override
    public void topConversation(ConversationTopReq req) {
        ChatConversation update = new ChatConversation();
        update.setId(req.getConversationId());
        Date now = new Date();
        update.setUpdateTime(now);
        if (req.getTop() == 1) {
            update.setTopTime(now);
        }
        this.updateById(update);
    }

    @Override
    public void updateLastPeerReadSeq(String id, String hasReadMsgSeq) {
        ChatConversation update = new ChatConversation();
        update.setId(id);
        update.setUpdateTime(new Date());
        update.setLastPeerReadSeq(hasReadMsgSeq);
        this.updateById(update);
    }

    @Override
    public void updateLastUserReadSeq(String id, String hasReadMsgSeq) {
        ChatConversation update = new ChatConversation();
        update.setId(id);
        update.setUpdateTime(new Date());
        update.setLastUserReadSeq(hasReadMsgSeq);
        this.updateById(update);
    }

    @Override
    public ApiMessageUnReadCountResponse countUnreadMessage(String userId) {

        ApiMessageUnReadCountResponse res = new ApiMessageUnReadCountResponse();
        res.setUnreadCount(this.baseMapper.selectUnreadMessageCount(userId));
        return res;
    }
}
